package com.dimong.www.loan.ui.frag.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;

import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.loadmore.SwipeRefreshHelper;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.dimong.loan.sdk.ui.WeakFragmentHandler;
import com.dimong.loan.sdk.ui.adapter.BaseRecyclerAdapter;
import com.dimong.www.loan.R;
import com.dimong.www.loan.app.MyApplication;
import com.dimong.www.loan.bean.MainBean;
import com.dimong.www.loan.db.CheckDao;
import com.dimong.www.loan.db.CheckModel;
import com.dimong.www.loan.db.CheckTotalDao;
import com.dimong.www.loan.ui.adapter.main.MainAdapter;
import com.dimong.www.loan.ui.base.BaseRefreshFragment;
import com.dimong.www.loan.ui.base.NoTitleActivity;
import com.dimong.www.loan.ui.base.TitleActivity;
import com.dimong.www.loan.ui.frag.AddCheckFrag;
import com.dimong.www.loan.widget.ActionBarView;
import com.dimong.www.loan.widget.LoanRefreshView;

import java.util.List;

public class MainOne2Frag extends BaseRefreshFragment {
    private SwipeRefreshLayout srl_frag_main_one;
    private RecyclerView rv_frag_main_one;
    private MainAdapter mainAdapter;
    private SwipeRefreshHelper mSwipeRefreshHelper;
    private HandlerThread loadData;
    private Handler loadDataHandler;
    private CheckDao checkDao;
    private List<CheckModel> checkModels;
    private WeakFragmentHandler weakHandler;
    private CheckTotalDao checkTotalDao;
    private ActionBarView actionBarView;
    private int checkSize;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkSize = 0;
            showRefreshLoading();
            getData();
        }
    };

    @Override
    public void beforeInitView() {

    }

    @Override
    public void initView() {
        super.initView();
        actionBarView = (ActionBarView) findViewById(R.id.title);
        srl_frag_main_one = (SwipeRefreshLayout) findViewById(R.id.srl_frag_main_one);
        rv_frag_main_one = (RecyclerView) findViewById(R.id.rv_frag_main_one);
        rv_frag_main_one.setItemAnimator(null);
    }

    @Override
    public void setViewStatus() {
        actionBarView.setTitle("账单");
        actionBarView.setLeftImgVisible(View.GONE);
        actionBarView.setOnRightText("账单明细", new ActionBarView.OnRightTextClickListener() {
            @Override
            public void onClick(View img) {
                Intent intent = new Intent(getActivity(), NoTitleActivity.class);
                intent.putExtra(":fragment_name", CheckDetailFrag.class.getName());
                intent.putExtra(":fragment_args", new Bundle());
                getActivity().startActivity(intent);
            }
        });
        checkDao = new CheckDao(MyApplication.getAppContext());
        checkTotalDao = new CheckTotalDao(MyApplication.getAppContext());
        rv_frag_main_one.setLayoutManager(new LinearLayoutManager(getActivity()));
        mainAdapter = new MainAdapter();
        rv_frag_main_one.setAdapter(new RecyclerAdapterWithHF(mainAdapter));

        mSwipeRefreshHelper = new SwipeRefreshHelper(srl_frag_main_one, rv_frag_main_one);
        mSwipeRefreshHelper.setLoadMoreEnable(true);
        mSwipeRefreshHelper.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                getData();
            }
        });
        mSwipeRefreshHelper.setOnSwipeRefreshListener(new SwipeRefreshHelper.OnSwipeRefreshListener() {
            @Override
            public void onfresh() {
                checkSize = 0;
                getData();
            }
        });

        mainAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int position) {
                MainBean mainBean = (MainBean) mainAdapter.getItem(position);
                if (mainBean.getObject() instanceof CheckModel) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("checkModel", (CheckModel) mainBean.getObject());
                    Intent intent = new Intent(getActivity(), TitleActivity.class);
                    intent.putExtra(":fragment_name", AddCheckFrag.class.getName());
                    intent.putExtra(":fragment_args", bundle);
                    getActivity().startActivity(intent);
                }
            }
        });
        srl_frag_main_one.setVisibility(View.GONE);

        setLoanReloadClick(new LoanRefreshView.LoanReloadClick() {
            @Override
            public void onRefreshClick() {
                showRefreshLoading();
                getData();
            }
        });

        loadData = new HandlerThread("loadData");
        loadData.start();
        loadDataHandler = new Handler(loadData.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                checkModels = checkDao.getCheckList(checkSize);
                weakHandler.sendEmptyMessage(0);
            }
        };

        weakHandler = new WeakFragmentHandler(this);

        showRefreshLoading();
        getData();

        findViewById(R.id.add_check).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), TitleActivity.class);
                intent.putExtra(":fragment_name", AddCheckFrag.class.getName());
                intent.putExtra(":fragment_args", new Bundle());
                getActivity().startActivity(intent);
            }
        });

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("REFRESH_CHECK");
        LocalBroadcastManager.getInstance(MyApplication.getAppContext()).registerReceiver(receiver, intentFilter);
    }

    @Override
    public int getViewResourceId() {
        return R.layout.frag_main_one2;
    }

    public void getData() {
        loadDataHandler.sendEmptyMessage(0);
    }

    @Override
    public void handleFragmentMessage(Message msg) {
        showRefreshSuccess();
        srl_frag_main_one.setVisibility(View.VISIBLE);
        mSwipeRefreshHelper.refreshComplete();
        super.handleFragmentMessage(msg);
        if (checkSize == 0) {
            mainAdapter.clear();
        }
        if (checkModels != null && checkModels.size() != 0) {
            checkSize += checkModels.size();
            for (int i = 0; i < checkModels.size(); i++) {
                MainBean mainBean = new MainBean();
                mainBean.setObject(checkModels.get(i));
                mainBean.setType(MainAdapter.ITEM_CHECK);
                if (mainAdapter.getItemCount() == 0) {
                    MainBean mainBean1 = new MainBean();
                    mainBean1.setType(MainAdapter.ITEM_CHECK_HEAD);
                    mainBean1.setObject(checkTotalDao.findOneRecord(checkModels.get(i).getYear(), checkModels.get(i).getMonth(), checkModels.get(i).getDay()));
                    mainAdapter.addData(mainBean1);
                } else {
                    for (int j = mainAdapter.getItemCount() - 1; j >= 0; j--) {
                        MainBean mainBean2 = (MainBean) mainAdapter.getItem(j);
                        if (mainBean2.getType() == MainAdapter.ITEM_CHECK) {
                            CheckModel checkModel = (CheckModel) mainBean2.getObject();
                            if (checkModel.getYear() != checkModels.get(i).getYear()
                                || checkModel.getMonth() != checkModels.get(i).getMonth()
                                || checkModel.getDay() != checkModels.get(i).getDay()) {
                                MainBean mainBean1 = new MainBean();
                                mainBean1.setType(MainAdapter.ITEM_CHECK_HEAD);
                                mainBean1.setObject(checkTotalDao.findOneRecord(checkModels.get(i).getYear(), checkModels.get(i).getMonth(), checkModels.get(i).getDay()));
                                mainAdapter.addData(mainBean1);
                            }
                            break;
                        }
                    }
                }
                mainAdapter.addData(mainBean);
            }
            mSwipeRefreshHelper.loadMoreComplete(true);
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        } else {
            mSwipeRefreshHelper.loadMoreComplete(false);
            mSwipeRefreshHelper.setLoadMoreEnable(false);
        }

        if (mainAdapter.getItemCount() == 0) {
            srl_frag_main_one.setVisibility(View.GONE);
            showNoData("还没有开始记账\n赶快开始吧!");
        }
        checkModels.clear();
        mainAdapter.updateChange();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(MyApplication.getAppContext()).unregisterReceiver(receiver);
    }

    @Override
    public RelativeLayout getContainView() {
        return (RelativeLayout) findViewById(R.id.rl_frag_main_one);
    }
}
